package com.example.esaclient;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.test.PerformanceTestCase;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class TwitterLogin extends Activity {

	 // Constants
    /**
     * Register your here app https://dev.twitter.com/apps/new and get your
     * consumer key and secret
     * */
    static String TWITTER_CONSUMER_KEY = "RUMoRPLvEHqN9dPoFIiwQ";
    static String TWITTER_CONSUMER_SECRET = "krqcrLoTxiG3cudESjArlpxAMbnfvkbf77ic9MyyE";
 
    // Preference Constants
    static String PREFERENCE_NAME = "twitter_oauth";
    static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
    static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
    static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
    static final String PREF_KEY_TWITTER_USERNAME = "";
    
 
    static final String TWITTER_CALLBACK_URL   = "esaclient://callback";
 
    // Twitter oauth urls
 // Twitter oauth urls
    static final String URL_TWITTER_AUTH = "auth_url";
    static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
    static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
    public String user_ID="2";
 
    // Progress dialog
    ProgressDialog pDialog;
 
    // Twitter
    private static Twitter twitter;
    private static RequestToken requestToken;
     
    // Shared Preferences
    private static SharedPreferences mSharedPreferences;
     
    //Twitter AccessToken
    AccessToken accessToken;
    
    // Internet Connection detector
    private ConnectionDetector cd;
     
    // Alert Dialog Manager
    AlertDialogManager alert = new AlertDialogManager();
 
    //progress dialog for esa communication
    ProgressDialog dialog;
    public String TWusername; 
    public Boolean logged=false;
 
    //layout resources
    TextView txtTWuser;
    ImageButton bttTW;
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tw_access);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
         
        //setting layout resources
        txtTWuser= (TextView)findViewById(R.id.txtTWuser);
        bttTW   = (ImageButton) findViewById(R.id.bttTW);
        
        
        cd = new ConnectionDetector(getApplicationContext());
 
        // Check if Internet present
        if (!cd.isConnectingToInternet()) {
            // Internet Connection is not present
            alert.showAlertDialog(TwitterLogin.this, "Internet Connection Error",
                    "Please connect to working Internet connection", false);
            // stop executing code by return
            return;
        }
         
        // Check if twitter keys are set
        if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
            // Internet Connection is not present
            alert.showAlertDialog(TwitterLogin.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
            // stop executing code by return
            return;
        }
 
     
        // Shared Preferences
        mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
        
        /** This if conditions is tested once is
         * redirected from twitter page. Parse the uri to get oAuth
         * Verifier
         * */
        if (!isTwitterLoggedInAlready()) {
        	
        	bttTW.setBackgroundResource(R.drawable.tw_icon_off);
        	 txtTWuser.setText("Not logged in");
            Uri uri = getIntent().getData();
            if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
                // oAuth verifier
                String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
     
                try {
                    // Get the access token
                    accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
     
                    //Getting Twitter username
                    long userID = accessToken.getUserId();
                    User user = twitter.showUser(userID);
                    TWusername = user.getName();
                    
                
                    Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
                    
                   
                	dialog = ProgressDialog.show(TwitterLogin.this, "", "Contacting Esa Server. Please, Wait...", true);
                	dialog.show();                   
                    //Calling the webService for store the AccessToken
                    new InsertToken().execute(user_ID, accessToken.getToken()+";"+accessToken.getTokenSecret(), "Twitter", "",this);
                    
                } catch (Exception e) {                    
                    Log.e("Twitter Login Error", "> " + e.getMessage());
                }}}
        else{
        	//getting Twitter username from shared Prefs
        	TWusername= mSharedPreferences.getString(PREF_KEY_TWITTER_USERNAME, "");
        	bttTW.setBackgroundResource(R.drawable.tw_icon);
        	 txtTWuser.setText("Logged as "+ TWusername);
        	logged=true;
        }
            }
            
            
            /**
             * Function to login twitter
             * */
            public void loginToTwitter(View view) {
                // Check if already logged in
                if (!isTwitterLoggedInAlready()) {                     
                     ConfigurationBuilder builder = new ConfigurationBuilder();
                    builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
                    builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
                    Configuration configuration = builder.build();
                     
                    TwitterFactory factory = new TwitterFactory(configuration);
                    twitter = factory.getInstance();
         
                    try {
                    	  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                          StrictMode.setThreadPolicy(policy);
                        requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
                        Toast.makeText(getApplicationContext(),"Opening browser...", Toast.LENGTH_LONG).show();
                        this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
                    } catch (TwitterException e) {
                        e.printStackTrace();
                    }
                } else {
                   
                	 AlertDialog.Builder builder = new AlertDialog.Builder(this);
                     builder.setMessage("Are you sure you want to log out from Twitter?")
                            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                	logoutFromTwitter(); 
                                	
                                }
                            })
                            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    // User cancelled the dialog
                                }
                            });
                     builder.create();
                     builder.show();

                	
                }
            }
         
            /**
             * Check user already logged from shared preferences
             * 
             * */
            private boolean isTwitterLoggedInAlready() {
                // return twitter login status from Shared Preferences
                return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
            }
            
	public void esaResult(Boolean result) {

		if (result) {
			if (logged) { //logging out
			// Clear the shared preferences
                Editor e = mSharedPreferences.edit();
                e.remove(PREF_KEY_OAUTH_TOKEN);
                e.remove(PREF_KEY_OAUTH_SECRET);
                e.remove(PREF_KEY_TWITTER_LOGIN);
                e.remove(PREF_KEY_TWITTER_USERNAME);
                e.commit();
				bttTW.setBackgroundResource(R.drawable.tw_icon_off);
				txtTWuser.setText("Not logged in.");
				logged = false;
			} else { //logging in
				
			    // Shared Preferences
                Editor e = mSharedPreferences.edit(); 
                // After getting access token, access token secret
                // store them in application preferences
                e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
                e.putString(PREF_KEY_OAUTH_SECRET,accessToken.getTokenSecret());
                e.putString(PREF_KEY_TWITTER_USERNAME,TWusername);                    
                // Store login status - true
                e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
                e.commit(); // save changes 
				bttTW.setBackgroundResource(R.drawable.tw_icon);
				txtTWuser.setText("Logged as " + TWusername);
				logged = true;
			}
		}
		else{// do nothing and display error
			 alert.showAlertDialog(TwitterLogin.this, "ESA Connection Error",
	                    "Error contacting the ESA Server. Try again later.", false);
		}

		dialog.dismiss();
	}

            /**
             * Function to logout from twitter
             * It will just clear the application shared preferences
             * */
            private void logoutFromTwitter() {
             
                dialog = ProgressDialog.show(TwitterLogin.this, "", "Contacting Esa Server. Please, Wait...", true);
            	dialog.show();                   
                //Calling the webService for store the AccessToken
            	new DeleteToken().execute(user_ID, "Twitter", this);
              
            }            
            
    }

